local ffi = require("ffi");
ffi.cdef[[
typedef void* iconv_t;
iconv_t libiconv_open(const char* tocode, const char* fromcode);
size_t libiconv (iconv_t cd,  char* * inbuf, size_t *inbytesleft, char* * outbuf, size_t *outbytesleft);
int libiconv_close (iconv_t cd);
]];

local iconv_dll = ffi.load("libiconv-2.dll");

--print(iconv.libiconv_open);
function iconv_open(t1,t2)
    return iconv_dll.libiconv_open(t1,t2);
end

local cd = --iconv_open("shift-jis","utf-8");
    iconv_open("utf-8","shift-jis");

local cd2 =
    iconv_open("UCS-2","utf-8");

local cd3 =
    iconv_open("UCS-2","shift-jis");

local ucs_to_utf8_cd =
    iconv_open("utf-8","ucs-2");

function iconv_close(cd)
    return iconv_dll.libiconv_close(cd);
end

local isize = ffi.new('size_t[?]',4);
local i_ptr = ffi.new('char*[?]',4);
local i_buf = ffi.new('uint8_t[?]',1024*1024);
function iconv(cd,text)
    i_ptr[0] = ffi.cast('char*',text);
    i_ptr[1] = i_buf;
    isize[0] = #text;
    isize[1] = 1024*1024;
    local size = iconv_dll.libiconv(cd,i_ptr+0,isize+0,i_ptr+1,isize+1);
    return ffi.string(i_buf),size;
end

-- local t = "我们不是一个人";
-- local text,sz = iconv(cd,t);
-- print(t);
-- print(text,sz);

--单个字符
-- for byte1=0xa1,0xdf do
--     local t = string.char(byte1);
--     local c = iconv(cd,t);
--     local c2 = iconv(cd2,c); --utf8 -> ucs-2
--     print(c,string.format('%02X%02X',c2:byte(2) or 0,c2:byte(1)));
--     --print(t);
-- end

if(false)then
    for byte1=0x81,0x9f do
        function proc(byte2)
            local text = string.char(byte1) .. string.char(byte2);
            local c = iconv(cd,text);
            local c2 = iconv(cd2,c); --utf8 ->ucs-2
            print(c,string.format('%02X%02X',i_buf[1],i_buf[0]));
        end

        for byte2=0x40,0x7e do
            proc(byte2);
        end

        for byte2=0x80,0xfc do
            proc(byte2);
        end
    end
else
    print(cd3);
    for byte1=0x81,0x9f do
        function proc(byte2)
            local text = string.char(byte1) .. string.char(byte2);
            local c = iconv(cd3,text);  --shift-jis -> ucs-2
            local c2 = iconv(ucs_to_utf8_cd,c);
            --print(text,c);
            --io.stdout:write(i_buf[1],i_buf[2]);
            print(string.format('[0x%02X%02X] = 0x%02X%02X, //%s',byte1,byte2,i_buf[1],i_buf[0],text));
        end

        for byte2=0x40,0x7e do
            proc(byte2);
        end

        for byte2=0x80,0xfc do
            proc(byte2);
        end
    end
end


